/**
 * Created by lghdb on 2018/6/13.
 * 自动加载项目里面的controllers目录里面的路由实现自动加载路由
 */
var fs = require('fs');
var path = require('path');


function addControllers(router,dir) {
  var filepath = path.join(__dirname, dir);
  fs.readdirSync(filepath).filter((f) => {
    return f.endsWith('.js');
  }).forEach((f) => {
    var mapping = require(path.join(filepath, f));
    addMapping(router, mapping);
  });
}


function addMapping(router, mapping) {
  for(var url in mapping){
    if (url.startsWith('GET ')) {
      var path = url.substring(4);
      router.get(path, mapping[url]);
      console.log(`register router GET ${path} `)
    } else if (url.startsWith('POST ')) {
      var path = url.substring(5);
      router.post(path, mapping[url]);
      console.log(`register router POST ${path} `)
    } else if (url.startsWith('PUT ')) {
      var path = url.substring(4);
      router.put(path, mapping[url]);
      console.log(`register router PUT ${path} `)
    } else if (url.startsWith('DELETE ')) {
      var path = url.substring(7);
      router.del(path, mapping[url]);
      console.log(`register router DELETE ${path} `)
    }
  }
}

module.exports = function (dir) {
  dir = dir || 'controllers';
  router = require('koa-router')();
  addControllers(router, dir);
  return router.routes();
};
